package cn.fxzhang.leetcode.utils;

import cn.fxzhang.leetcode.common.ListNode;

/**
 * @author 张晓帆
 * @date 2021/3/30
 */
public class ListNodeUtil {

    /**
     * 将数组转化成链表结构
     * 如{3,2,4}转化成 3->2->4->null
     * @param nums
     * @return
     */
    public static ListNode buildListNode(int[] nums){
       ListNode next = null;
       for (int i = nums.length-1; i>=0; i--){
           ListNode listNode = new ListNode(nums[i], next);
           next = listNode;
       }
       return next;
    }

    /**
     * 将数组转化成翻转后的链表结构
     * 如{3,2,4}转化成 4->2->3->null
     * @param nums
     * @return
     */
    public static ListNode buildReverseListNode(int[] nums){
        ListNode next = null;
        for (int i = 0; i<nums.length; i--){
            ListNode listNode = new ListNode(nums[i], next);
            next = listNode;
        }
        return next;
    }

    /**
     * 比较两个链表的值是否相同
     * @param l1
     * @param l2
     * @return
     */
    public static boolean compare(ListNode l1, ListNode l2){
        while (l1 != null && l2 != null){
            if (l1.val != l2.val){
                return false;
            }
            l1 = l1.next;
            l2 = l2.next;
        }
        return l1 == null && l2 == null;
    }
}
